package com.sykj.seaflow.warm.core.expression;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.sykj.seaflow.warm.core.constant.FlowConstant;
import com.warm.flow.core.constant.FlowCons;
import com.warm.flow.core.expression.ExpressionStrategy;
import com.warm.flow.core.expression.ExpressionStrategyAbstract;
import com.warm.flow.core.utils.ExpressionUtil;

import java.util.Map;

public class ExpressionStrategySimpleOr implements ExpressionStrategy {

    @Override
    public String getType() {
        return FlowCons.splitAt + "simple_or" + FlowCons.splitAt;
    }


    /**
     * [{
     * 		key:'age',
     * 		cond:'ge',
     * 		value:'2',
     * 		next: 'and',
     * 	    }]
     */
    /**
     *
     *  重写eval  实现一组表达式的解析
     * @param expression @@eq@@|flag@@eq@@4
     * @param variable
     * @return
     */
    @Override
    public boolean eval(String expression, Map<String, Object> variable) {
        // 如果前面的通过， 这里就不满足了
        if((boolean) variable.getOrDefault(FlowConstant.SERIAL_NODE_BEFORE_COMPLETED, false)){
            return false;
        }
        Map<String, Object> formVar = (Map<String, Object>) variable.get("formData");
        JSONArray array = JSONUtil.parseArray(expression);
        for (int i = 0; i < array.size(); i++) {
            String key = array.getJSONObject(i).getStr("key");
            String cond = array.getJSONObject(i).getStr("cond");
            String v = array.getJSONObject(i).getStr("value");
//            @@eq@@|flag@@eq@@4
            String type = FlowCons.splitAt + cond + FlowCons.splitAt + "|"
                    + key + FlowCons.splitAt + cond +FlowCons.splitAt + v;
            if(ExpressionUtil.eval(type, formVar)){
                variable.put(FlowConstant.SERIAL_NODE_BEFORE_COMPLETED, true);
                return true;
            }
        }
        return false;

    }

}
